import { ReactElement, useRef, useEffect } from 'react'
import { DataSchema } from '../../ajax'
import { Modal, Form, FormInstance, message } from 'antd'
import UnitNumberInput from '@components/unitNumberInput'
import { awaitWrap } from '@js/tool'
import { updateRequest } from './ajax'
import Text from '@components/text'
const { Item } = Form

async function submitHandle (d: { [k: string]: any }, hide: () => void, refreshData: () => void): Promise<void> {
  const h = message.loading('提交中', 120)
  delete d.name
  const [e] = await awaitWrap(updateRequest(d))
  h()
  if (e === null) {
    hide()
    message.success('编辑成功').then(null, null)
    refreshData()
  }
}

interface Props {
  visible: boolean
  data: DataSchema | null
  pType: 'accepter' | 'processer' | 'manager'
  hide: () => void
  refreshData: () => void
}

function Main ({ visible, data, pType, hide, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  useEffect(() => {
    const c = formRef.current
    if (data !== null && c !== null) {
      c.setFieldsValue(data)
    }
  }, [data, formRef])
  return (
    <Modal title='编辑权重' visible={visible} onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} labelCol={{ flex: '88px' }} onFinish={async d => await submitHandle(d, hide, refreshData)}>
        <Item noStyle name='id'><span /></Item>
        <Item label='姓名' name='name'>
          <Text />
        </Item>
        {
          pType === 'accepter' && (
            <Item label='受理权重' name='accepter_case_weights'>
              <UnitNumberInput min={0} max={1} unit='' precision={2} />
            </Item>
          )
        }
        <Item label='办案权重' name='processer_case_weights'>
          <UnitNumberInput min={0} max={1} unit='' precision={2} />
        </Item>
        <Item label='非办案权重' name='work_weights'>
          <UnitNumberInput min={0} max={1} unit='' precision={2} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
